package com.kaiyidiannao.db;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import com.kaiyidiannao.data.DataCenter;

import java.util.Date;

public class RpcCacheDBDao {
	
	private static RpcCacheDBDao instance;
	
	private SQLiteDatabase mDatabase;
	private SQLiteOpenHelper dbHelper;

	private RpcCacheDBDao() {
		
	}
	
	public static RpcCacheDBDao getInstance() {
		if(instance == null) {
			synchronized (RpcCacheDBDao.class) {
				instance = new RpcCacheDBDao();
			}
		}
		return instance;
	}
	
	public void initialize(Context ctx) {
		dbHelper = new RpcCacheDBHelper(ctx, RpcCacheDBHelper.DB_RPC_CHCHE_TABLE_NAME, null, RpcCacheDBHelper.DB_RPC_CHCHE_VERSION);
		mDatabase = dbHelper.getWritableDatabase();
	}
	
	public void close() {
		mDatabase.close();
		dbHelper.close();
	}
	
	public RpcCacheDBRecord doQuery(String key) {
		if(TextUtils.isEmpty(key) || !reInitialize()) {
			return null;
		}
		RpcCacheDBRecord record = null;
		Cursor cursor = mDatabase.query(RpcCacheDBHelper.DB_RPC_CHCHE_TABLE_NAME, new String[]{"key", "body", "time"}, "key=?", new String[]{key}, null, null, null);
		if(cursor != null && cursor.getCount() > 0 && cursor.moveToFirst()) {
			record = new RpcCacheDBRecord();
			record.setKey(cursor.getString(cursor.getColumnIndex("key")));
			record.setBody(cursor.getString(cursor.getColumnIndex("body")));
			record.setTime(cursor.getString(cursor.getColumnIndex("time")));
		}
		cursor.close();
		return record;
	}
	
	public void doUpdate(RpcCacheDBRecord record) {
		if(record == null) {
			return;
		}
		if(doQuery(record.getKey()) == null) {
			insert(record);
		} else {
			update(record);
		}
	}
	
	public void doClear() {
		if(!reInitialize()) {
			return;
		}
		mDatabase.delete(RpcCacheDBHelper.DB_RPC_CHCHE_TABLE_NAME, null, null);
	}
	
	private void insert(RpcCacheDBRecord record) {
		if(record == null || !reInitialize()) {
			return;
		}
		if(TextUtils.isEmpty(record.getTime())) {
			record.setTime("" + new Date().getTime());
		}
		mDatabase.insert(RpcCacheDBHelper.DB_RPC_CHCHE_TABLE_NAME, null, record.convert2ContentValues());
	}
	
	private void update(RpcCacheDBRecord record) {
		if(record == null || !reInitialize()) {
			return;
		}
		if(TextUtils.isEmpty(record.getTime())) {
			record.setTime("" + new Date().getTime());
		}
		mDatabase.update(RpcCacheDBHelper.DB_RPC_CHCHE_TABLE_NAME, record.convert2ContentValues(), "key=?", new String[]{record.getKey()});
	}
	
	private boolean reInitialize() {
		if(DataCenter.context != null) {
			if(mDatabase == null) {
				initialize(DataCenter.context);
			} else if(!mDatabase.isOpen()) {
				mDatabase = dbHelper.getWritableDatabase();
			}
		}
		if(mDatabase == null || !mDatabase.isOpen()) {
			return false;
		}
		return true;
	}

}
